import axios from 'axios'

const instance = axios.create({
  baseURL: '/oneDimension',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(config => {
  // 确保数值类型正确
  if (config.data) {
    config.data = {
      id: parseInt(config.data.id),
      length: parseFloat(config.data.length),
      num: parseInt(config.data.num)
    }
  }
  return config
})

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.data.code !== 1) {
      return Promise.reject(new Error(response.data.msg))
    }
    return response.data
  },
  error => {
    if (error.response) {
      return Promise.reject(new Error(
        `[${error.response.status}] ${error.response.data?.msg || 'Unknown error'}`
      ))
    }
    return Promise.reject(error)
  }
)

export default {
  add: (data) => instance.post('/part/add', data),
  delete: (data) => instance.delete('/part/delete', { data }),
  update: (data) => instance.put('/part/update', data)
}